var colortypes = ['','info','success','warning','danger'];
moment.locale('zh_CN');
window.utils = {
	showNotification:function(message,type,from,align){
    		from = from || 'top';
    		align = align || 'center';
    		type = type || 0;
    		return $.notify({
        	    message: message
            },{
                element:$('body', parent.document).length>0?$('body', parent.document)[0]:'body',
                position:'fixed',
                type: colortypes[type],
                timer: 1000,
                placement: {
                    from: from,
                    align: align
                }
            });
	},
    showAlert:function(message,option){
        option = option || {
            sub:'',
            type:'success'
        };
        swal(message, option.sub, option.type);
    },
    showConfirm:function(message,option,sure,cancel){
        var default_option = {
            title: message,
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: true,
            closeOnCancel: true
        };
        option = $.extend(default_option,option);
        swal(option,function(isconfirm){
            if(isconfirm){
                if(sure){
                    sure()
                }
            }else{
                if(cancel){
                    cancel();
                }
            }
        })
    },
    jsonToParams:function(param, key, encode) {
        if (param == null) return '';
        var paramStr = '';
        var t = typeof(param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
        } else {
            for (var i in param) {
                var k = key == null ? i : key + '[' + i + ']';
                paramStr += utils.jsonToParams(param[i], k, encode);
            }
        }
        return paramStr;
    },
    modal:function (title,content,options,extendOptions,callback) {
        if (!options){
            options = ['取消','确认'];
        }
        if ($.isFunction(content)){
            var contentFunc = content;
            content = "数据加载中，请稍后。";
        }
        if ($.isFunction(extendOptions)){
            callback = extendOptions;
            extendOptions = {
                style:'modal-select-promotion'
            };
        }
        if (!extendOptions.style){
            extendOptions['style'] = 'modal-select-promotion';
        }

        if ($('#myModal').length == 0){
            var tpl = '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'+
                '<div class="modal-dialog  '+extendOptions['style']+'" role="document">'+
                '<div class="modal-content">'+
                '<div class="modal-header">'+
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                '<h4 class="modal-title" id="myModalLabel">'+title+'</h4>'+
                '</div>'+
                '<div class="modal-body">'+
                content+
                '</div>'+
                '<div class="modal-footer">';
            if (options.length == 1){
                tpl += '<button type="button" class="btn btn-success btn-fill">'+options[0]+'</button>';
            }else {
                tpl += '<button type="button" class="btn btn-default btn-simple" data-dismiss="modal">'+options[0]+'</button>' +
                    '<button type="button" class="btn btn-success btn-fill">'+options[1]+'</button>';
            }
            tpl +='</div>'+
                '</div>'+
                '</div>'+
                '</div>';
            $('body').append(tpl);
        }else {
            $('#myModal .modal-dialog').attr('class','modal-dialog '+extendOptions.style);
            $('#myModal .modal-title').html(title);
            $('#myModal .modal-body').html(content);
            var footer = '';
            if (options.length == 1){
                footer += '<button type="button" class="btn btn-success btn-fill">'+options[0]+'</button>';
            }else {
                footer += '<button type="button" class="btn btn-default btn-simple" data-dismiss="modal">'+options[0]+'</button>' +
                    '<button type="button" class="btn btn-success btn-fill">'+options[1]+'</button>';
            }
            $('#myModal .modal-footer').html(footer);
        }
        $('#myModal .btn-default').unbind('click').on('click',function () {
            callback(0);
        })
        $('#myModal .btn-success').unbind('click').on('click',function () {
            callback(1);
        })
        $('#myModal').modal('show');
        if (typeof contentFunc !== 'undefined'){
            contentFunc($('#myModal'));
        }

        return $('#myModal');
    },
    zclip:function (elm,text) {
        if(elm.clip) {
            return;
        }
        if (!text){
            text = $(elm).data('text');
        }
        require(['jquery.zclip'], function(){
            $(elm).zclip({
                path: '/js/admin/zclip/ZeroClipboard.swf',
                copy: text,
                afterCopy: function(){
                    utils.showNotification('成功复制到剪切板',2)
                }
            });
            elm.clip = true;
        })
    },
    qrcode:function (elm,options) {
        if(elm.qrcode) {
            return;
        }
        if (!options.text){
            options.text = $(elm).data('text');
        }
        require(['jquery.qrcode'], function(){
            $(elm).qrcode(options);
            elm.qrcode = true;
        });

    }

};
function getFileName(fileUrl){
    return fileUrl.substring(fileUrl.lastIndexOf('/')+1,fileUrl.lastIndexOf("."));
}
function getIdSelections($table) {
    return $.map($table.bootstrapTable('getSelections'), function (row) {
        return row.id
    });
}
function initUploadImageFile(id){
    var container = $('body');
    if (id){
        container = $(id);
    }
    var uploadFiles = container.find('input[data-target="uploadImageFile"]');
    $.each(uploadFiles,function(i,v){
        $_self = $(v);
        var initialPreview = [];
        var initialPreviewConfig = [];
        var previewImage = $('input[name="'+$_self.attr('data-for')+'"]').attr('data-preview')||$('input[name="'+$_self.attr('data-for')+'"]').val();
        if(previewImage){
            initialPreview.push(previewImage);
            initialPreviewConfig.push({key:getFileName(previewImage)})
        }
        $_self.fileinput({
            //allowedFileTypes:['image'],
            language:'zh',
            initialPreview:initialPreview,
            initialPreviewConfig:initialPreviewConfig,
            initialPreviewShowDelete: true,
            deleteUrl:'',
            initialPreviewAsData: true,
            multiple:false,
            allowedFileExtensions:['jpg','jpeg','png','gif','ico','bmp'],
            uploadUrl: "/tmp/upload",
            overwriteInitial:true,
            dropZoneEnabled:false,
            showRemove: false,
            layoutTemplates: {
                actionDelete: ''
            }
        }).on('fileuploaded', function(event, data, previewId, index) {
            if (data.response.code == 0){
                if (typeof window.uploadFilesSuccess !== 'undefined'){
                    window.uploadFilesSuccess(data.response.result,$(event.target).attr('data-for'));
                }
                $('#'+previewId).attr('data-code',getFileName(data.response.result.attachment));
                $('input[name="'+$(event.target).attr('data-for')+'"]').val(data.response.result.original);
            }else {
                utils.showNotification('上传文件失败',3);
            }

        }).on('filecleared',function(event){
            //console.log(event,1);
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        }).on('filedeleted',function(event,key){
            //console.log(event,key,2);
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        }).on('filereset',function(event){
           // console.log(event,3);
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        }).on('filesuccessremove',function(event,id){
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        });
    })
};
function initUploadMulImageFile(id){
    var container = $('body');
    if (id){
        container = $(id);
    }
    var uploadFiles = container.find('input[data-target="uploadMulImageFile"]');
    $.each(uploadFiles,function(i,v){
        $_self = $(v);
        var initialPreview = [];
        var initialPreviewConfig = [];
        $('input[name="'+$_self.attr('data-for')+'"]').each(function(mi,mv){
            var previewImage = $(mv).attr('data-preview')||$(mv).val();


            $(mv).attr('data-code',getFileName(previewImage));
            initialPreview.push(previewImage);
            initialPreviewConfig.push({key:getFileName(previewImage)});
        });
        $_self.fileinput({
            language:'zh',
            initialPreview:initialPreview,
            initialPreviewConfig:initialPreviewConfig,
            deleteUrl:'/tmp/upload',
            initialPreviewAsData: true,
            allowedFileExtensions:['jpg','jpeg','png','gif','ico','bmp'],
            uploadUrl: "/tmp/upload",
            overwriteInitial:false,
            multiple:true,
            dropZoneEnabled:false
        }).on('fileuploaded', function(event, data, previewId, index) {
            if (data.response.code == 0){
                $('#'+previewId).attr('data-code',getFileName(data.response.result.attachment));
                $(event.target).parent().append('<input type="hidden" value="'+data.response.result.original+'" data-code="'+getFileName(data.response.result.attachment)+'" name="'+$(event.target).attr('data-for')+'">');
                if (typeof window.uploadFilesSuccess !== 'undefined'){
                    window.uploadFilesSuccess(data.response.result,$(event.target).attr('data-for'));
                }
            }else {
                utils.showNotification('上传文件失败',3);
            }
        }).on('filecleared',function(event){
            //console.log(event,1);
            $('input[name="'+$_self.attr('data-for')+'"]').remove();
        }).on('filedeleted',function(event,key){
            //console.log(event,key,2);
           // $('#'+$(event.target).attr('data-for')).val('');
            $('input[data-code="'+key+'"]').remove();
        }).on('filereset',function(event){
           // console.log(event,3);
            $('input[name="'+$_self.attr('data-for')+'"]').remove();
        }).on('filesuccessremove',function(event,id){
            console.log($('#'+id).attr('data-code'));
            $('input[data-code="'+$('#'+id).attr('data-code')+'"]').remove();
        });
    });
}
function initUploadMediaFile(id,type){
    var container = $('body');
    if (id){
        container = $(id);
    }
    var uploadFiles = container.find('input[data-target="uploadMediaFile"]');
    $.each(uploadFiles,function(i,v){
        $_self = $(v);
        var initialPreview = [];
        var initialPreviewConfig = [];
        var previewImage = $('input[name="'+$_self.attr('data-for')+'"]').attr('data-preview')||$('input[name="'+$_self.attr('data-for')+'"]').val();
        if(previewImage){
            initialPreview.push(previewImage);
            initialPreviewConfig.push({key:getFileName(previewImage)})
        }
        $_self.fileinput({
            allowedFileTypes:['video', 'audio'],
            language:'zh',
            // initialPreview:initialPreview,
            // initialPreviewConfig:initialPreviewConfig,
            showPreview:false,
            deleteUrl:'',
            // initialPreviewAsData: true,
            multiple:false,
            allowedFileExtensions:["'"+type+"'"],
            uploadUrl: "/tmp/upload",
            overwriteInitial:true,
            dropZoneEnabled:false
        }).on('fileuploaded', function(event, data, previewId, index) {
            if (data.response.code == 0){
                alert(data);
                // if (typeof window.uploadFilesSuccess !== 'undefined'){
                //     window.uploadFilesSuccess(data.response.result,$(event.target).attr('data-for'));
                // }
                // $('#'+previewId).attr('data-code',getFileName(data.response.result.attachment));
                // $('input[name="'+$(event.target).attr('data-for')+'"]').val(data.response.result.original);
            }else {
                utils.showNotification('上传文件失败',3);
            }

        }).on('filecleared',function(event){
            console.log(event,1);
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        }).on('filedeleted',function(event,key){
            //console.log(event,key,2);
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        }).on('filereset',function(event){
            // console.log(event,3);
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        }).on('filesuccessremove',function(event,id){
            $('input[name="'+$(event.target).attr('data-for')+'"]').val('');
        });
    })
}

function initTinymce(){
    tinymce.init({
        selector: '.tinymceEditor',
        skin: 'lightgray',
        height : 300,
        width:410,
        menubar: false,
        language: 'zh_CN',
        plugins: [
            "advlist autolink lists link image  charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor"
        ],
        // 'undo redo  | styleselect | bold underline italic | link  alignleft aligncenter alignright alignjustify | fontselect fontsizeselect'
        toolbar: [
            'undo redo  | styleselect | bold italic | link  alignleft aligncenter alignright alignjustify | fontselect | fontsizeselect'
        ],
    });
}
function initDatetimepicker(id){
    var container = $('body');
    if (id){
        container = $(id);
    }
    var datetimepickers = container.find('.datetimepicker');
    datetimepickers.each(function(i,v){
        $(v).datetimepicker({
            format:'YYYY-MM-DD HH:mm',
            locale:'zh-cn',
            icons: {
                time: "fa fa-clock-o",
                date: "fa fa-calendar",
                up: "fa fa-chevron-up",
                down: "fa fa-chevron-down",
                previous: 'fa fa-chevron-left',
                next: 'fa fa-chevron-right',
                today: 'fa fa-screenshot',
                clear: 'fa fa-trash',
                close: 'fa fa-remove'
            }
         });
    })
    
}
function initTimepicker(id){
    var container = $('body');
    if (id){
        container = $(id);
    }
    var datetimepickers = container.find('.timepicker');
    datetimepickers.datetimepicker({
        format:'HH:mm',
        locale:'zh-cn',
        icons: {
            time: "fa fa-clock-o",
            date: "fa fa-calendar",
            up: "fa fa-chevron-up",
            down: "fa fa-chevron-down",
            previous: 'fa fa-chevron-left',
            next: 'fa fa-chevron-right',
            today: 'fa fa-screenshot',
            clear: 'fa fa-trash',
            close: 'fa fa-remove'
        }
    });
    
}

function initColorPickerAndSwitch(id) {
    var container = $('body');
    if (id){
        container = $(id);
    }
    container.find('.colorPicker').colorpicker();
}

var default_table_option = {
    toolbar: ".toolbar",

    clickToSelect: false,
    showRefresh: true,
    search: true,
    toolbarAlign:'right',
    locale:'zh-CN',
    showToggle: false,
    showColumns: false,
    pagination: true,
    idField:'id',
    searchAlign: 'left',
    sortOrder:'desc',
    buttonsAlign:'right',
    sidePagination:'server',
    queryParams:function(params){
        return $.extend(params,tableAjaxParams||{});
    },
    pageSize: 8,
    pageList: [8,10,25,50,100],

    formatShowingRows: function(pageFrom, pageTo, totalRows){
        //do nothing here, we don't want to show the text "showing x of y from..."
    },
    formatRecordsPerPage: function(pageNumber){
        return pageNumber + " rows visible";
    },
    icons: {
        refresh: 'fa fa-refresh',
        toggle: 'fa fa-th-list',
        columns: 'fa fa-columns',
        detailOpen: 'fa fa-plus-circle',
        detailClose: 'fa fa-minus-circle',

    }
}



$().ready(function(){

    //登录页面，相关js
	var login_page = $('.login-page');
	if(login_page.length > 0 ){
		lbd.checkFullPageBackgroundImage();
    
    setTimeout(function(){
        // after 1000 ms we add the class animated to the login/register card
        $('.card').removeClass('card-hidden');
    }, 700)
    $('.login-form').validate({
    	submitHandler:function(form){
    		var obj = $(form).serialize();
            $.isLoading({text:'登录中，请稍后...'});
            $.post(location.href,obj,function(res){
                $.isLoading('hide');
                if(res.status === 1){
                    var notify = utils.showNotification(res.info,2);
                    setTimeout(function(){
                        notify.close();
                        window.location.href="/admin/home/index"
                    },500);
                    
                }else{
                    utils.showNotification(res.info,3);
                }
            });
    		
    		
    		return false;
    	}
    });
	}
    //解锁页面，相关js
	var lock_page = $('.lock-page');
	if(lock_page.length > 0 ){
		lbd.checkFullPageBackgroundImage();
        $('.lockForm').validate({
            submitHandler:function(form){
                var obj = $(form).serialize();
                $.isLoading({text:'解锁中，请稍后...'});
                $.post(location.href,obj,function(res){
                    $.isLoading('hide');
                    if(res.status === 1){
                        utils.showNotification(res.info,2);
                        setTimeout(function(){
                            window.location.href="/admin/home/index"
                        },500);
                    }else{
                        utils.showNotification(res.info,3);
                        if(res.outlogin){
                            setTimeout(function(){
                                window.location.href="/admin/auth/login"
                            },500);
                        }
                        
                    }
                });
                return false;
            }
        });
	}
    initUploadImageFile();
    initUploadMulImageFile();
    initTinymce();
    initDatetimepicker();
    initTimepicker();
    initColorPickerAndSwitch();
    $('.add-btn').on('click',function(){
        var url = $(this).attr('data-url');
        window.location.href = url;
    });
    $('.form-horizontal').validate({
        submitHandler:function(form){
            var url = $(form).attr('action')||location.href;
            var back = $(form).data('back');
            var obj = $(form).serialize();
            if(typeof beforeSubmitValidate !== 'undefined'){
               if(!beforeSubmitValidate()){
                   return false;
               }
            }
            $.isLoading({text:'数据提交中，请稍后...'});
            $.post(url,obj,function(res){
                $.isLoading('hide');
                if(res.code == 0){
                    utils.showNotification(res.message||'保存成功',2);
                    setTimeout(function(){
                        if(typeof submitSuccessCallBack !== 'undefined'){
                            submitSuccessCallBack();
                        }else{
                            if (back){
                                window.location.href = back;
                            }else {
                                history.go(-1);
                            }

                        }
                    },400);
                }else{
                    utils.showNotification(res.message,3);
                }
                
            })
            return false;
        }
    });

    if($('#bootstrap-table-container').length >0){
        var $table = $('#bootstrap-table-container');
        var dataUrl = $table.attr('data-url');
        default_table_option['url'] = dataUrl;
         if(typeof window.table_option === 'undefined'){
             window.table_option = {

             }
         }
        default_table_option = $.extend(default_table_option,window.table_option);
        $table.bootstrapTable(default_table_option);
        $('.remove-btn').on('click',function(){
            if(getIdSelections($table).length === 0){
                utils.showNotification('请选择需要删除的数据',3);
                return false;
            }
            var event = new CustomEvent("table-delete-item", { "detail": getIdSelections($table) });
            $table[0].dispatchEvent(event);
        })
        $table[0].addEventListener('table-delete-item',function(e){
            var id = e.detail;
            var deleteUrl = $table.attr('data-delete-url');
            utils.showConfirm('是否删除选中的数据？',{},function(){
                $.isLoading({text:'删除中，请稍后...'});
                $.post(deleteUrl,utils.jsonToParams(id,'id'),function(res){
                    $.isLoading('hide');
                    if(res.code === 0){
                        utils.showNotification(res.message,2);
                        $table.bootstrapTable('refresh');
                    }else{
                        utils.showNotification(res.message,3);
                    }
                });
            });
            
            
        });
        $(window).resize(function () {
            $table.bootstrapTable('resetView');
        });
    }

});

function htmlspecialchars_decode (string, quote_style) {
    // http://jsphp.co/jsphp/fn/view/htmlspecialchars_decode
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined') {
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            } else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded
    string = string.replace(/&amp;/g, '&');

    return string;
}

/**
 *@param {string} url 完整的URL地址
 *@returns {object} 自定义的对象
 *@description 用法示例：var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');

 myURL.file='index.html'

 myURL.hash= 'top'

 myURL.host= 'abc.com'

 myURL.query= '?id=255&m=hello'

 myURL.params= Object = { id: 255, m: hello }

 myURL.path= '/dir/index.html'

 myURL.segments= Array = ['dir', 'index.html']

 myURL.port= '8080'

 yURL.protocol= 'http'

 myURL.source= 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'

 */
function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}
